package com.candy.common.domain;

import com.candy.common.exception.IErrorCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

/**
 * 通用返回对象
 * @author rong xi
 * @version 1.0
 * @date 2023/09/14 18:28
 */
@Data
@NoArgsConstructor
@Schema(name = "通用返回对象",description = "通用返回对象")
public class Result<T>{

	/**
	 * 响应代码 200-响应正常 400-参数错误 500-服务异常
	 */
	@Schema(description = "响应代码 200-正常 400-参数错误 401-没有权限 500-服务异常")
	private Integer code = HttpStatus.OK.value();

	/**
	 * 失败消息
	 */
	@Schema(description = "失败消息")
	private String msg = "";

	/**
	 * 响应时间戳
	 */
	@Schema(description = "响应时间戳")
	private Long timestamp = System.currentTimeMillis();

	/**
	 * 返回的数据
	 */
	@Schema(description = "返回数据")
	private T data;

	/**
	 * 成功结果
	 * @param data 数据
	 * @return 返回结果
	 */
	public static <T> Result<T> success(T data) {
		Result<T> result = new Result<>();
		result.setData(data);
		return result;
	}

	/**
	 * 成功结果
	 * @return 返回结果
	 */
	public static <T> Result<T> success() {
		return new Result<>();
	}

	/**
	 * 失败结果-无数据
	 * @param errorCode 错误枚举
	 * @return 返回结果
	 */
	public static <T> Result<T> fail(IErrorCode errorCode) {
		Result<T> result = new Result<>();
		result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
		result.setMsg(errorCode.getCode()+":"+errorCode.getDesc());
		return result;
	}

	/**
	 * 失败结果-无数据
	 * @param errorCode 错误枚举
	 * @param params 动态参数
	 * @return 返回结果
	 */
	public static <T> Result<T> fail(IErrorCode errorCode,Object... params) {
		Result<T> result = new Result<>();
		result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
		result.setMsg(errorCode.getCode()+":"+String.format(errorCode.getDesc(),params));
		return result;
	}

	/**
	 * 失败结果-无数据
	 * @param code 错误码
	 * @param errorCode 错误枚举
	 * @param params 动态参数
	 * @return 返回结果
	 */
	public static <T> Result<T> fail(Integer code,IErrorCode errorCode,Object... params) {
		Result<T> result = new Result<>();
		result.setCode(code);
		result.setMsg(errorCode.getCode()+":"+String.format(errorCode.getDesc(),params));
		return result;
	}

	/**
	 * 失败结果-无数据
	 * @param msg 错误枚举
	 * @return 返回结果
	 */
	public static <T> Result<T> fail(String msg) {
		Result<T> result = new Result<>();
		result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
		result.setMsg(msg);
		return result;
	}

	/**
	 * 失败结果-无数据
	 * @param msg 错误枚举
	 * @param code 响应码
	 * @return 返回结果
	 */
	public static <T> Result<T> fail(Integer code,String msg) {
		Result<T> result = new Result<>();
		result.setCode(code);
		result.setMsg(msg);
		return result;
	}
}
